package com.oa.official.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.oa.official.mapper.SysRoleMapper;
import com.oa.official.mapper.SysUserRoleMapper;
import com.oa.official.service.SysRoleService;
import com.oa.official.entity.system.SysRole;
import com.oa.official.entity.system.SysUserRole;
import com.oa.official.response.Result;
import com.oa.official.vo.system.AssginRoleVo;
import com.oa.official.vo.system.SysRoleQueryVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleServiceImpl implements SysRoleService {

    @Resource
    private SysRoleMapper sysRoleMapper;

    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    /**
     * 角色条件分页查询
     * @param page
     * @param limit
     * @param sysRoleQueryVo
     * @return
     */
    @Override
    public Result list(Integer page, Integer limit, SysRoleQueryVo sysRoleQueryVo) {
        Page<SysRole> page2 = new Page<>(page,limit);
        String roleName = sysRoleQueryVo.getRoleName();
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.hasText(roleName),SysRole::getRoleName,roleName);
        Page<SysRole> sysRolePage = sysRoleMapper.selectPage(page2, lambdaQueryWrapper);
        return Result.success(sysRolePage);
    }

    /**
     * 新增角色
     * @param sysRole
     * @return
     */
    @Override
    public Result save(SysRole sysRole) {
        int row = sysRoleMapper.insert(sysRole);
        return row > 0 ? Result.success() : Result.error("角色添加失败");
    }

    /**
     * 根据角色id查询
     * @param id
     * @return
     */
    @Override
    public Result findByRoleId(Long id) {
        SysRole sysRole = sysRoleMapper.selectById(id);
        return Result.success(sysRole);
    }

    /**
     * 根据id删除角色
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Long id) {
        int row = sysRoleMapper.deleteById(id);
        return row > 0 ? Result.success() : Result.error("删除角色失败");
    }

    /**
     * 批量删除角色
     * @param ids
     * @return
     */
    @Override
    public Result batchRemove(List<Long> ids) {
        int row = sysRoleMapper.deleteBatchIds(ids);
        return row > 0 ? Result.success() : Result.error("批量删除角色失败");
    }

    /**
     * 修改角色
     * @param sysRole
     * @return
     */
    @Override
    public Result update(SysRole sysRole) {
        int row = sysRoleMapper.updateById(sysRole);
        return row > 0 ? Result.success() : Result.error("修改角色失败");
    }
    /**
     * 查询当前用户的角色和全部的角色列表
     * @param userId
     * @return
     */
    @Override
    public Result toAssign(Long userId) {
        //查询所有角色
        List<SysRole> allSysRoles = sysRoleMapper.selectList(null);
        //根据userid,查询当前用户的角色
        LambdaQueryWrapper<SysUserRole> queryChainWrapper = new LambdaQueryWrapper<>();
        queryChainWrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> existSysUserRoles = sysUserRoleMapper.selectList(queryChainWrapper);
        //获取所有的角色id
        //获取当前用户的所有角色id
        List<SysRole> assginRoles = new ArrayList<>();
        if(existSysUserRoles != null && !existSysUserRoles.isEmpty()){
            List<Long> roleIds = existSysUserRoles
                    .stream()
                    .map(SysUserRole::getRoleId)
                    .collect(Collectors.toList());
            LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysRole::getId,roleIds);
            List<SysRole> sysRoles = sysRoleMapper.selectList(queryWrapper);
            assginRoles.addAll(sysRoles);
        }
        //封装起来
        Map<String,Object> map = new HashMap<>();
        map.put("assginRoleList",assginRoles);
        map.put("allRolesList",allSysRoles);
        return Result.success(map);
    }

    /**
     * 为用户分配角色
     * @param assginRoleVo
     * @return
     */
    @Override
    @Transactional
    public Result doAssign(AssginRoleVo assginRoleVo) {
        Long userId = assginRoleVo.getUserId();
        List<Long> roleIdList = assginRoleVo.getRoleIdList();
        //1:把用户之前分配的角色先删除
        LambdaQueryWrapper<SysUserRole> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysUserRole::getUserId,userId);
        sysUserRoleMapper.delete(lambdaQueryWrapper);
        //2:再重新分配角色
        if(!StringUtils.isEmpty(roleIdList)){
            roleIdList.forEach(roleId->{
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(userId);
                sysUserRole.setRoleId(roleId);
                sysUserRoleMapper.insert(sysUserRole);
            });
        }
        return Result.success();
    }

}